package tw.com.softleader.gary.movie.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import tw.com.softleader.gary.movie.model.MovieModel;
import tw.com.softleader.gary.movie.service.MovieService;

public class MovieServiceImpl implements MovieService {
	
	private Collection<MovieModel> models = new ArrayList<MovieModel>();


	public Collection<MovieModel> getAll() {
		return models;
	}
	
	public MovieModel getById(Long id) {
		
		for(MovieModel model:models) {
			if(model.getId().equals(id)) {
				return model;
			}
		}
		
		return null;
		
	}

	public void insert(MovieModel movie) throws Exception {
		
		if(movie == null || movie.getId() == null) {
			throw new Exception("the ID is null error");
		}
		
		
		for(MovieModel model:models) {
			if(model.getId().equals(movie.getId())) {
				throw new Exception("the ID is duplicated");
			}
		}
		
		models.add(movie);
	}

	public void update(MovieModel movie) throws Exception {
		
		if(movie == null || movie.getId() == null) {
			throw new Exception("the ID is null error");
		}
		
		for(MovieModel model:models) {
			if(model.getId().equals(movie.getId())) {
				model.setLocalName(movie.getLocalName());
				model.setName(movie.getName());
			}
		}
		
	}

	public void delete(MovieModel movie) {
		
		// it will cause "java.util.ConcurrentModificationException"
		/*
		for(MovieModel model:models) {
			if(model.getId().equals(movie.getId())) {
				models.remove(model);
			}
		}
		*/
		
		Iterator<MovieModel> itr = models.iterator();
		while(itr.hasNext()) {

			if ( itr.next().getId().equals(movie.getId()) ) {
				
				System.out.println("Deleting id="+movie.getId());
				itr.remove();
			}
			
		}
		

	}
	
	

}
